package top.lyjwn.todo.common.template;

import com.alibaba.fastjson2.JSONObject;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

/**
 * 分页数据
 *
 * @author luoyujie
 */
public class Paging implements Pageable {

    /**
     * 页码
     */
    private long page = 1;
    /**
     * 内页条数
     */
    private int limit = 10;

    /**
     * 关键字
     */
    private String keyWord = "";

    /**
     * 排序
     */
    private Sort sort;

    public Paging() {


    }

    public Paging(long page, int limit) {
        this.page = page;
        this.limit = limit;
    }

    public Paging(long page, int limit, String keyWord) {
        this.page = page;
        this.limit = limit;
        this.keyWord = keyWord;
    }

    public Paging(JSONObject jsonObject) {
        this.page = jsonObject.getLongValue("page");
        this.limit = jsonObject.getInteger("limit");
        this.keyWord = jsonObject.getString("keyWord");
    }

    public void setSort(Sort sort) {
        this.sort = sort;
    }

    public long getIndex() {
        return page <= 1 ? 0 : ((page - 1) * limit);
    }

    public long getPage() {
        return page < 1 ? 1 : page;
    }

    public void setPage(long page) {
        this.page = page;
    }

    public int getLimit() {
        return limit;
    }

    public void setLimit(int limit) {
        this.limit = limit;
    }

    public String getKeyWord() {
        return keyWord;
    }

    public void setKeyWord(String keyWord) {
        this.keyWord = keyWord;
    }

    public Pageable withPage(int pageNumber)
    {
        this.page =pageNumber;
        return this;

    }

    @Override
    public int getPageNumber() {
        Long page = getPage();
        return page.intValue();
    }

    @Override
    public int getPageSize() {
        return getLimit();
    }

    @Override
    public long getOffset() {
        return getIndex();
    }

    @Override
    public Sort getSort() {
        return sort == null ? Sort.unsorted() : sort;
    }


    @Override
    public Pageable next() {
        Paging paging = new Paging(getPage(), getLimit());
        paging.setPage(getPage() + 1);
        return paging;
    }

    @Override
    public Pageable previousOrFirst() {
        Paging paging = new Paging(getPage(), getLimit());
        paging.setPage(getPage() - 1);
        return paging;
    }

    @Override
    public Pageable first() {
        return new Paging(1, 10);
    }

    @Override
    public boolean hasPrevious() {
        return getPage() != 0;
    }

}
